<?php
/**
 * 简单的日志过滤器
 *
 * @version $Id: ISimpleLogFilter.php 312 2008-04-23 16:29:38Z iwind $
 * @package util.log.filter
 * @since 0.0.2
 */
class ISimpleLogFilter extends IObject implements ILogFilter {
	/**
	 * 过滤
	 * %{a} remote IP address
	 * %{t} Time the request was received (RFC 822 format)
	 * %{m} The request method
	 * %{U} The URI path requested.
	 * %Y，%m，%d ... date format
	 * 
	 * @param string &$message 需要过滤的信息
	 * @param IFilterChain $chain 过滤器链
	 * @since 0.0.2
	 */
	public function doFilter(&$message, $chain = null) {
		$message = preg_replace_callback("/%\\{([a-zA-Z])\\}/", array($this, "filterParseCallback"), $message);
		$message = preg_replace_callback("/%([a-zA-Z])\\b/", array($this, "filterParseDateCallback"), $message);
		
		//continue next filter
		if ($chain != null) {
			$chain->doNext();
		}
	}
	
	
	/**
	 * 替换普通符号的回调函数
	 *
	 * @param array $match preg匹配结果
	 * @return string
	 * @since 0.0.2
	 * 
	 */
	private function filterParseCallback($match) {
		$char = $match[1];
		$formats = array("a", "t", "m", "f", "U");
		if (in_array($char, $formats)) {
			$request = IRequest::singleton();
			switch ($char) {
				case "a":
					return $request->ip();
				case "t":
					return date("r");
				case "m":
					return $request->method();
				case "U":
					return $request->uri();
			}
		}
		return $match[0];
	}	
	
	/**
	 * 替换日期符号的回调函数
	 *
	 * @param array $match preg匹配结果
	 * @return string
	 * @since 0.0.2
	 */
	private function filterParseDateCallback($match) {
		$dateFormats = array("Y", "m", "d", "H", "i", "s");
		if (in_array($match[1], $dateFormats)) {
			return date($match[1]);
		}
		return $match[0];
	}	
}

?>